<template>
  <div class="my-order-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="订单时间" class="date-form-item">
          <el-date-picker
            v-model="searchForm.bookingDate"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
            style="width: 180px;"
          />
          <div class="date-tip">
            <i class="el-icon-warning"></i>
            <span>按时间检索是指订单创建时间，不是预约时间段！</span>
          </div>
        </el-form-item>
        <el-form-item label="预约状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="待支付" :value="0" />
            <el-option label="已支付" :value="1" />
            <el-option label="使用中" :value="2" />
            <el-option label="已完成" :value="3" />
            <el-option label="已取消" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <el-table
      v-loading="loading"
      :data="orderList"
      border
      style="width: 100%"
    >
      <el-table-column
        prop="orderNumber"
        label="订单编号"
        width="120"
      />
      <el-table-column
        prop="roomName"
        label="自习室"
        width="120"
      />
      <el-table-column
        label="预约时段"
        min-width="200"
      >
        <template slot-scope="scope">
          <div>
            <div>日期：{{ formatDate(scope.row.startTime) }}</div>
            <div>时间：{{ formatTime(scope.row.startTime) }} - {{ formatTime(scope.row.endTime) }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="amount"
        label="费用"
        width="100"
        align="center"
      >
        <template slot-scope="scope">
          ￥{{ scope.row.amount.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="orderStatus"
        label="状态"
        width="100"
        align="center"
      >
        <template slot-scope="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ scope.row.orderStatus }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="orderTime"
        label="创建时间"
        width="160"
        align="center"
      />
      <el-table-column
        label="操作"
        width="160"
        align="center"
      >
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status === 0"
            type="text"
            size="small"
            @click="handleCancel(scope.row)"
          >取消预约</el-button>
          <el-divider
            v-if="scope.row.status === 0"
            direction="vertical"
          ></el-divider>
          <el-button
            type="text"
            size="small"
            style="color: #f56c6c;"
            @click="handleDelete(scope.row)"
          >删除订单</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        :current-page="page"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'MyOrder',
  data() {
    return {
      loading: false,
      searchForm: {
        bookingDate: '',
        status: ''
      },
      orderList: [],
      page: 1,
      limit: 10,
      total: 0
    }
  },
  created() {
    this.fetchOrders()
  },
  methods: {
    // 格式化日期
    formatDate(dateStr) {
      const date = new Date(dateStr)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
    },
    // 格式化时间
    formatTime(dateStr) {
      const date = new Date(dateStr)
      return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
    },
    // 获取订单列表
    async fetchOrders() {
      try {
        this.loading = true
        const res = await request({
          url: '/api/booking/booking-order/findOrderByUser',
          method: 'get',
          params: {
            pageNum: this.page,
            pageSize: this.limit,
            bookingDate: this.searchForm.bookingDate || undefined,
            status: this.searchForm.status || undefined
          }
        })
        if (res.code === 200 && res.data) {
          this.orderList = res.data.list || []
          this.total = res.data.total || 0
          this.page = res.data.pageNum || 1
          this.limit = res.data.pageSize || 10
        } else {
          this.orderList = []
          this.total = 0
        }
      } catch (error) {
        console.error('获取订单列表失败:', error)
        this.$message.error('获取订单列表失败')
        this.orderList = []
        this.total = 0
      } finally {
        this.loading = false
      }
    },
    // 取消预约
    handleCancel(row) {
      this.$confirm('确认取消该预约吗？', '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          const res = await request({
            url: `/api/booking/booking-order/cancel/${row.id}`,
            method: 'post'
          })
          if (res.code === 200) {
            this.$message.success('取消预约成功')
            this.fetchOrders()
          }
        } catch (error) {
          console.error('取消预约失败:', error)
          this.$message.error('取消预约失败')
        }
      })
    },
    // 删除订单
    handleDelete(row) {
      this.$confirm('确认删除该订单记录吗？', '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          const res = await request({
            url: `/api/booking/booking-order/delete/${row.id}`,
            method: 'delete'
          })
          if (res.code === 200) {
            this.$message.success('删除成功')
            this.fetchOrders()
          }
        } catch (error) {
          console.error('删除订单失败:', error)
          this.$message.error('删除订单失败')
        }
      })
    },
    // 搜索
    handleSearch() {
      this.page = 1
      this.fetchOrders()
    },
    // 重置搜索
    resetSearch() {
      this.searchForm = {
        bookingDate: '',
        status: ''
      }
      this.handleSearch()
    },
    // 改变每页显示数量
    handleSizeChange(val) {
      this.limit = val
      this.fetchOrders()
    },
    // 改变页码
    handleCurrentChange(val) {
      this.page = val
      this.fetchOrders()
    },
    // 获取状态类型
    getStatusType(status) {
      const statusMap = {
        0: 'warning',   // 待支付
        1: 'success',   // 已支付
        2: 'primary',   // 使用中
        3: 'info',      // 已完成
        4: 'danger'     // 已取消
      }
      return statusMap[status] || 'info'
    }
  }
}
</script>

<style scoped>
.my-order-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
}

.search-container {
  margin-bottom: 20px;
}

.date-form-item {
  margin-bottom: 25px !important;
}

.date-tip {
  position: absolute;
  margin-top: 5px;
  font-size: 12px;
  color: #f56c6c;
  white-space: nowrap;
  line-height: 1.2;
}

.date-tip i {
  margin-right: 4px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style> 